//
//  HMOauthViewController.swift
//  新浪微博-4-13v1.0
//
//  Created by 黎永锋 on 16/4/13.
//  Copyright © 2016年 黎永锋. All rights reserved.
// https://api.weibo.com/oauth2/authorize?client_id=3445107834&redirect_uri=http://www.baidu.com

import UIKit
import SVProgressHUD

class HMOauthViewController: UIViewController {
    
    //在loadView里面赋值不用设置view的大小
    override func loadView() {
        view = webView
        
        //设置webView的代理
        webView.delegate = self
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //设置背景颜色,不然在modal出来的时候,会透明看到后面的控制器,效果很奇怪
        view.backgroundColor = GlobalBGColor
        
        setupNavitaionBar()
        
        //加载授权界面
        let url = oauthURL()
        let request = NSURLRequest(URL: url)
        webView.loadRequest(request)
    }
    
    //拼接Oauth授权登录界面的url (GET)
    private func oauthURL() ->NSURL{
    
        let urlString = OauthUrl + "?client_id=" + client_id + "&redirect_uri=" + redirect_uri
        
        return NSURL(string: urlString)!
    }
    
    private func setupNavitaionBar(){
    
        navigationItem.leftBarButtonItem = UIBarButtonItem.init(title: "填充", style: UIBarButtonItemStyle.Plain, target: self, action: Selector("autoFill"))
        navigationItem.rightBarButtonItem = UIBarButtonItem.init(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: Selector("close"))
    }

    //MARK: - 按钮点击事件
    @objc private func autoFill(){
    
//        HMPrint("autoFill")
        //使用webView执行js代码
        let js = "document.getElementById('userId').value = '15507732614';document.getElementById('passwd').value = '15lyfswb'"
        webView.stringByEvaluatingJavaScriptFromString(js)
    }
    
    @objc private func close(){
    
//        HMPrint("close")
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    // MARK: -懒加载
    private lazy var webView: UIWebView = UIWebView()
}

//MARK: -
extension HMOauthViewController: UIWebViewDelegate{

    // webView是否要去加载一个请求
    // true: 放行,可以加载
    // false: 拦住,不去加载
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        let urlString = request.URL?.absoluteString
        HMPrint("webView是否要去加载一个请求:\(urlString)")
        
        // 判断是否是授权回调地址
        let isRedirectURL = urlString!.hasPrefix(redirect_uri)
        
        if !isRedirectURL {
        
            //不是授权回调地址,让他加载
            return true
            
        }else{
        
            //授权回调地址,点击的是取消或授权
            //判断点击的是取消还是授权按钮, 如果?后面是code=开头就是授权按钮
            //query是get请求?后面的东西
            let query = request.URL?.query
            HMPrint("query:\(query)")
            
            let codeString = "code="
            //判断query是否是code=开头
            if query!.hasPrefix(codeString) {
            
                //query 是以code=开头,授权按钮
                HMPrint("授权按钮点击了:\(query)")
                //截取 code=704e417687c8d6237d35216c747dfd24 里面code=后面的内容
//                let index = codeString.endIndex
//                let code = query!.substringFromIndex(index)
                
                //截取字符串转成NSString
                let code = (query! as NSString).substringFromIndex(codeString.characters.count)
                HMPrint("code:\(code)")
            }else{
            
                //取消按钮
                HMPrint("取消按钮点击了")
                //关闭控制器
                
                close()
            }
            
            return false
        }
    }
    //webView加载完成
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    //webView加载失败
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        //当设置showErrorWithStatus会将其他的HUDdismiss
        SVProgressHUD.showErrorWithStatus("网络不给力")
        SVProgressHUD.setDefaultMaskType(SVProgressHUDMaskType.None)
    }
}

